package com.kanche.bigbaby.collection;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.kanche.bigbaby.collection.domain.Photo;
import com.squareup.tape.Task;

import java.io.File;
import java.util.Map;

import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;

//import com.kkche.bss.domain.Photo;


/**
 * Uploads the specified file to imgur.com.
 */
public class ImageUploadTask implements Task<ImageUploadTask.Callback> {
    private static final long serialVersionUID = 126142781146165256L;

    private static final String TAG = "Merchant:ImageUploadTask";
    private static final Handler MAIN_THREAD = new Handler(Looper.getMainLooper());
    private final Photo photo;
    private final File photoFile;
    private final long batchId;
    private final Context context;

    public ImageUploadTask(Photo photo, long batchId, Context context) {
        this.batchId = batchId;
        this.photo = photo;
        this.context = context;
        this.photoFile = new File(photo.getUri());
    }

    @Override
    public void execute(final Callback callback) {
        TypedFile file = new TypedFile("image/jpeg", photoFile);
        getBSSService().uploadPhoto(file, "origin", new retrofit.Callback<Map<String, String>>() {
            @Override
            public void success(Map<String, String> map, Response response) {
                final Photo result = new Photo();
                result.setKey(photo.getKey());
                result.setUri(map.get("result"));
                MAIN_THREAD.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess(result, batchId);
                    }
                });
            }

            @Override
            public void failure(final RetrofitError error) {
                MAIN_THREAD.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(error, photo, batchId);
                    }
                });
            }
        });
    }

    private BSSService getBSSService() {
        return BSSService.Creator.create(context);
    }

    public interface Callback {
        void onSuccess(Photo photo, long batchId);

        void onFailure(RetrofitError error, Photo photo, long batchId);
    }
}
